package com.zabra.zl.ui.runing;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.orhanobut.logger.Logger;
import com.zabra.zl.Config;
import com.zabra.zl.R;
import com.zabra.zl.base.BaseMvpActivity;
import com.zabra.zl.data.RunningListBean;
import com.zabra.zl.data.RunningTypeBean;
import com.zabra.zl.myview.state_layout.OtherView;
import com.zabra.zl.ui.runing.contract.RunningContract;
import com.zabra.zl.ui.runing.presenter.RunningPresenter;
import com.zabra.zl.utils.DateUtils;
import com.zabra.zl.utils.DialogUtils;
import com.zabra.zl.utils.MaptoJsonUtils;
import com.zabra.zl.utils.SelectorUtils;
import com.zabra.zl.utils.SharedPreferencesUtil;
import com.zabra.zl.utils.ShowDialogUtils;
import com.zabra.zl.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RunningActivity extends BaseMvpActivity<RunningPresenter> implements RunningContract.View {


    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.tv_startdata)
    TextView tvStartdata;
    @BindView(R.id.tv_enddata)
    TextView tvEnddata;
    @BindView(R.id.otherview)
    OtherView otherview;
    @BindView(R.id.refresh)
    PullToRefreshLayout refresh;
    private List<RunningListBean.FlowsBean> list = new ArrayList<>();
    private ItemAdp adp;
    private TimePickerView pvCustomTime;
    private List<RunningTypeBean.BusisBean> typeList;
    private Dialog dialog;
    private String strTypeCode = "", strStartData = "", strEndData = "";
    private int page = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_running;
    }

    @Override
    public void initView() {
        otherview.setHolder(mHolder);
        mPresenter = new RunningPresenter();
        mPresenter.attachView(this);
        tvTitle.setText("资金流水");


        initParameter();

        refresh.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                page = 1;
                keyList.add("debtorId");
                keyList.add("busiCode");
                keyList.add("startTime");
                keyList.add("endTime");
                keyList.add("currentPage");
                keyList.add("pageSize");
                valueList.add(strUserid);
                valueList.add(strTypeCode);
                valueList.add(strStartData);
                valueList.add(strEndData);
                valueList.add(page + "");
                valueList.add(Config.PAGESIZE);
                mPresenter.getDataFresh(MaptoJsonUtils.Simple(keyList, valueList));
                keyList.clear();
                valueList.clear();
            }

            @Override
            public void loadMore() {
                page++;
                keyList.add("debtorId");
                keyList.add("busiCode");
                keyList.add("startTime");
                keyList.add("endTime");
                keyList.add("currentPage");
                keyList.add("pageSize");
                valueList.add(strUserid);
                valueList.add(strTypeCode);
                valueList.add(strStartData);
                valueList.add(strEndData);
                valueList.add(page + "");
                valueList.add(Config.PAGESIZE);
                mPresenter.getDataLoadMore(MaptoJsonUtils.Simple(keyList, valueList));
                keyList.clear();
                valueList.clear();
            }
        });

    }

    @Override
    public void showLoading() {
        dialog = DialogUtils.showDialog_progressbar(this);
    }

    @Override
    public void hideLoading() {
        DialogUtils.closeDialog(dialog);
    }

    @Override
    public void onError(Throwable throwable) {
        DialogUtils.closeDialog(dialog);
        refresh.finishRefresh();
        refresh.finishLoadMore();
    }

    /**
     * @param bean 类型字典
     */
    @Override
    public void onSuccess(RunningTypeBean bean) {
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            typeList = bean.getBusis();
            List<String> nameList = new ArrayList<>();
            for (RunningTypeBean.BusisBean busisBean : typeList) {
                nameList.add(busisBean.getBusiName());
            }
            OptionsPickerView pvNoLinkOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    tvAll.setText(typeList.get(options1).getBusiName());
                    strTypeCode = typeList.get(options1).getBusiCode();
                    initParameter();
                    Logger.d("name---->" + typeList.get(options1).getBusiName() + "code---" + typeList.get(options1).getBusiCode());
                }
            }).setCancelColor(Color.parseColor("#999999"))
                    .setSubmitColor(Color.parseColor("#ff3025"))
                    .setTitleBgColor(Color.parseColor("#ffffff"))
                    .setContentTextSize(14)
                    .setSubCalSize(14)
                    .setContentTextSize(18)
                    .setCancelText("全部")
                    .setOnCancelClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            tvAll.setText("全部");
                            strTypeCode = "";
                            initParameter();
                        }
                    })
                    .build();
            pvNoLinkOptions.setNPicker(nameList, null, null);
            pvNoLinkOptions.show();
        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }

    @Override
    public void onSuccess(RunningListBean bean, String token) {
        SharedPreferencesUtil.getInstance(this).putSP("token", token);
        initData(bean);
    }

    @Override
    public void onSuccessFresh(RunningListBean bean) {
        refresh.finishRefresh();
        initData(bean);
    }

    @Override
    public void onSuccessLoadMore(RunningListBean bean) {
        refresh.finishLoadMore();
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            list.addAll(bean.getFlows());
            //延迟更新数据，避免卡顿
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    adp.notifyItemRangeChanged(0, bean.getFlows().size());
                }
            }, 500);
            if (bean.getFlows().size() == 0) {
                ToastUtil.showToast(this, "没有更多数据");
            }
        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }

    private void initData(RunningListBean bean) {
        list.clear();
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            list.addAll(bean.getFlows());
            if (list.size() == 0) {
                otherview.showEmptyView();
                refresh.setCanLoadMore(false);
            } else {
                otherview.showContentView();
                refresh.setCanLoadMore(true);
            }
            recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            recycler.setNestedScrollingEnabled(false);
            adp = new ItemAdp(R.layout.item_item_running, list);
            recycler.setAdapter(adp);
            adp.openLoadAnimation();
        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }

    @OnClick({R.id.back, R.id.tv_startdata, R.id.tv_enddata, R.id.tv_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_startdata:
                initCustomTimePickerStart();
                break;
            case R.id.tv_enddata:
                initCustomTimePickerEnd();
                break;
            case R.id.tv_all:
                mPresenter.getTypeData();
                break;
        }
    }

    public void initCustomTimePickerStart() {
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tvStartdata.setText(DateUtils.getHM(date, "yyyy/MM/dd"));
                strStartData = DateUtils.getHM(date, "yyyy-MM-dd");
                initParameter();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        TextView ivCancel = v.findViewById(R.id.tv_cancle);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tvStartdata.setText("起始日期");
                                strStartData = "";
                                initParameter();
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.parseColor("#999999"))
                .build();
        pvCustomTime.show();
    }

    public void initCustomTimePickerEnd() {
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tvEnddata.setText(DateUtils.getHM(date, "yyyy/MM/dd"));
                strEndData = DateUtils.getHM(date, "yyyy-MM-dd");
                initParameter();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        TextView ivCancel = v.findViewById(R.id.tv_cancle);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                strEndData = "";
                                initParameter();
                                tvEnddata.setText("结束日期");
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(0, 0, 0, 40, 0, -40)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.parseColor("#999999"))
                .build();
        pvCustomTime.show();
    }

    private void initParameter() {
        page = 1;
        keyList.add("debtorId");
        keyList.add("busiCode");
        keyList.add("startTime");
        keyList.add("endTime");
        keyList.add("currentPage");
        keyList.add("pageSize");
        valueList.add(strUserid);
        valueList.add(strTypeCode);
        valueList.add(strStartData);
        valueList.add(strEndData);
        valueList.add(page + "");
        valueList.add(Config.PAGESIZE);
        mPresenter.getData(MaptoJsonUtils.Simple(keyList, valueList));
        keyList.clear();
        valueList.clear();
    }

}
